package com.baizhi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.entity.User;
import com.baizhi.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserServiceImpl us;
    @PostMapping("users")
    public Map<String,Object> login(@RequestBody User u,HttpSession session) {
        String code = (String) session.getAttribute("code");
        if (code.equalsIgnoreCase(u.getYanzheng())){
            boolean login = us.login(u.getEmail(), u.getPassword());
            if (login) {
                session.setAttribute("user",u);
                return new HashMap() {{
                    put("success", true);
                }};
            }
        }
        return new HashMap() {{
            put("default",false);
        }};
    }
    @GetMapping("users/yanzheng")
    public void yanzheng(HttpServletResponse response, HttpSession s){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 34, 4, 20);
        ServletOutputStream stream=null;
        try {
             stream = response.getOutputStream();
             lineCaptcha.write(stream);
             //获取验证码生成的值
            String code = lineCaptcha.getCode();
            //将这个值放入session中
            s.setAttribute("code",code);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("tuichu")
    public void tuichu(HttpSession session){
        session.removeAttribute("user");
    }
}
